@extends('layouts.base')

@section('title', '分类管理')

@push('styles')
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            /*border-radius: 10px;*/
            /*margin-bottom: 20px;*/
            position: relative;
        }

        .page-title {
            font-size: 1.5rem;
            font-weight: 600;
            margin: 0;
            text-align: center;
        }

        .category-tabs {
            display: flex;
            background: white;
            border-radius: 0;
            /*margin-bottom: 20px;*/
            overflow: hidden;
            box-shadow: none;
            border-bottom: 1px solid #e2e8f0;
        }

        .category-tab {
            flex: 1;
            padding: 12px;
            background: white;
            border: none;
            font-size: 1rem;
            font-weight: 500;
            color: #666;
            cursor: pointer;
            transition: all 0.2s;
        }

        .category-tab.active {
            background: #667eea;
            color: white;
        }

        .category-content {
            background: white;
            border-radius: 0;
            padding: 20px;
            box-shadow: none;
        }

        .category-list::-webkit-scrollbar {
            width: 6px;
        }

        .category-list::-webkit-scrollbar-track {
            background: #f1f5f9;
            border-radius: 3px;
        }

        .category-list::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }

        .category-list::-webkit-scrollbar-thumb:hover {
            background: #94a3b8;
        }

        .category-section {
            display: none;
        }

        .category-section.active {
            display: block;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #f0f0f0;
        }

        .section-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
        }

        .add-category-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: background 0.2s;
        }

        .add-category-btn:hover {
            background: #218838;
        }

        .list-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e2e8f0;
        }

        .list-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #333;
            margin: 0;
        }

        .add-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 6px 12px;
            border-radius: 6px;
            font-size: 0.85rem;
            cursor: pointer;
            transition: background 0.2s;
        }

        .add-btn:hover {
            background: #218838;
        }

        .category-list {
            list-style: none;
            padding: 0;
            margin: 0;
            background: none;
        }

        .category-item {
            /*padding: 16px 20px;*/
            margin-bottom: 8px;
            /*background: white;*/
            /*border: 1px solid #e2e8f0;*/
            /*border-radius: 8px;*/
            display: ruby;
            align-items: center;
            transition: all 0.2s ease;
            cursor: move;
            background: none;
            /*box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);*/
        }
        .category-item:hover {
            background: none;
        }

        .category-info {
            display: flex;
            align-items: center;
            flex: 1;
            gap: 12px;
        }

        .drag-handle {
            color: #999;
            cursor: move;
            font-size: 18px;
            width: 24px;
            text-align: center;
            flex-shrink: 0;
        }

        .drag-handle:hover {
            color: #667eea;
        }

        .category-icon {
            width: 40px;
            height: 40px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            background: #f0f4ff;
            border: 1px solid #e2e8f0;
            flex-shrink: 0;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .category-icon:hover {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }

        .category-name {
            font-size: 16px;
            font-weight: 500;
            color: #333;
            margin: 0;
            flex: 1;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 6px;
            transition: background-color 0.2s;
            line-height: 1.4;
            display: flex;
            flex-direction: column;
            gap: 4px;
        }

        .category-name:hover {
            background-color: #f0f4ff;
        }

        .name-text {
            font-size: 16px;
            font-weight: 500;
            color: #333;
        }

        .subcategory-count {
            font-size: 12px;
            color: #666;
            font-weight: 400;
        }

        .category-actions {
            display: flex;
            gap: 8px;
            flex-shrink: 0;
        }

        .action-btn {
            width: 36px;
            height: 36px;
            border-radius: 6px;
            border: 1px solid #e2e8f0;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            transition: all 0.2s ease;
            background: white;
            color: #666;
        }

        .edit-btn {
            background-color: #48bb78;
            color: white;
            border-color: #48bb78;
        }

        .edit-btn:hover {
            background-color: #38a169;
            border-color: #38a169;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(72, 187, 120, 0.3);
        }

        .delete-btn {
            background-color: #f56565;
            color: white;
            border-color: #f56565;
        }

        .delete-btn:hover {
            background-color: #e53e3e;
            border-color: #e53e3e;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(245, 101, 101, 0.3);
        }

        .subcategory-btn {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }

        .subcategory-btn:hover {
            background-color: #5a67d8;
            border-color: #5a67d8;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #4a5568;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* 图标选择器样式 */
        .icon-selector {
            position: relative;
        }

        .selected-icon {
            width: 60px;
            height: 60px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            cursor: pointer;
            background: white;
            transition: all 0.2s ease;
        }

        .selected-icon:hover {
            border-color: #667eea;
            background: #f0f4ff;
        }

        .icon-picker {
            position: absolute;
            top: 70px;
            left: 0;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 16px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            z-index: 1000;
            width: 280px;
        }

        .icon-grid {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 8px;
        }

        .icon-option {
            width: 40px;
            height: 40px;
            border: 1px solid #e2e8f0;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            cursor: pointer;
            transition: all 0.2s ease;
            background: white;
        }

        .icon-option:hover {
            border-color: #667eea;
            background: #f0f4ff;
            transform: scale(1.1);
        }

        .icon-option.selected {
            border-color: #667eea;
            background: #667eea;
            color: white;
        }

        .modal-test {
            top: 300px;
        }
    </style>
@endpush

@section('content')
<div class="">
    <!-- 页面头部 -->
    <div class="page-header">
        <button class="back-btn" onclick="window.location.href = '{{ route('user.books') }}'">‹</button>
        <h1 class="page-title">分类管理</h1>
    </div>

    <!-- 分类标签页 -->
    <div class="category-tabs">
        <button class="category-tab active" data-type="2">支出分类</button>
        <button class="category-tab" data-type="1">收入分类</button>
    </div>

    <!-- 分类内容 -->
    <div class="category-content">
        <!-- 支出分类 -->
        <div class="category-section active" id="expense-section">
            <div class="section-header">
                <h2 class="section-title">支出分类</h2>
                <button class="add-category-btn" onclick="showAddCategoryModal(2)">+ 添加分类</button>
            </div>
            <div class="category-list-container">
                <ul class="category-list" id="expense-list">
                    <!-- 动态加载支出分类 -->
                </ul>
            </div>
        </div>

        <!-- 收入分类 -->
        <div class="category-section" id="income-section">
            <div class="section-header">
                <h2 class="section-title">收入分类</h2>
                <button class="add-category-btn" onclick="showAddCategoryModal(1)">+ 添加分类</button>
            </div>
            <div class="category-list-container">
                <ul class="category-list" id="income-list">
                    <!-- 动态加载收入分类 -->
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑分类弹窗 -->
<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content modal-test">
            <div class="modal-header">
                <h5 class="modal-title" id="categoryModalTitle">添加分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="category-form">
                    <div class="form-group">
                        <label class="form-label">分类名称</label>
                        <input type="text" class="form-input" id="category-name" placeholder="请输入分类名称" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">描述说明（描述可以让AI分类得更精准的）</label>
                        <input type="text" class="form-input" id="category-description" placeholder="格式：xx和xx的费用（可选）">
                    </div>
                    <div class="form-group">
                        <label class="form-label">选择图标</label>
                        <div class="icon-selector">
                            <input type="text" class="form-input" id="emoji-search" placeholder="输入中文搜索图标...">
                            <div class="emoji-selector" id="emoji-selector">
                            </div>
                            <div class="emoji-option-no-results" style="display: none" id="emoji-selector-empty">-- 没有找到匹配的emoji --</div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-category">确定</button>
            </div>
        </div>
    </div>
</div>

<!-- 分类迁移确认弹窗 -->
<div class="modal fade" id="categoryMigrationModal" tabindex="-1" role="dialog" aria-labelledby="categoryMigrationModalTitle" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content modal-test">
            <div class="modal-header">
                <h5 class="modal-title" id="categoryMigrationModalTitle">删除分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="migration-message"></p>
                <div class="form-group">
                    <label for="target-category">选择目标分类：</label>
                    <select class="form-control" id="target-category">
                        <option value="">请选择目标分类</option>
                    </select>
                </div>
                <div class="form-group" id="subcategory-selection-container" style="display: none;">
                    <label for="target-subcategory">选择目标子分类：</label>
                    <select class="form-control" id="target-subcategory">
                        <option value="">请选择目标子分类</option>
                    </select>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-migration">确认迁移并删除</button>
            </div>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script src="{{ asset('/js/sortable.min.js') }}"></script>
<script src="{{ asset('js/emoji-search.js') }}"></script>
<script>
        $(document).ready(function() {
            // 加载分类数据
            loadCategories();

            // 标签页切换
            $('.category-tab').click(function() {
                const type = $(this).data('type');
                $('.category-tab').removeClass('active');
                $(this).addClass('active');

                $('.category-section').removeClass('active');
                if (type == 2) {
                    $('#expense-section').addClass('active');
                } else {
                    $('#income-section').addClass('active');
                }
            });

            // 确认添加/编辑分类
            $('#confirm-category').click(function() {
                if (currentCategoryId) {
                    updateCategory();
                } else {
                    createCategory();
                }
            });

            // 初始化拖拽排序
            initSortable();
        });

        const bookId = {{ $book->id }};
        let currentCategoryType = 2;
        let currentCategoryId = null;
        let selectedIcon = '📁';
        let expenseSortable = null;
        let incomeSortable = null;

        // 加载分类数据
        function loadCategories() {
            $.get(`{{ route('user.categories.data', $book->id) }}`, function(response) {
                if (response.success) {
                    renderCategories(response.categories);
                } else {
                    showError('加载分类失败');
                }
            }).fail(function() {
                showError('网络错误，请重试');
            });
        }

        // 渲染分类列表
        function renderCategories(categories) {
            const expenseList = $('#expense-list');
            const incomeList = $('#income-list');

            expenseList.empty();
            incomeList.empty();

            categories.forEach(function(category) {
                const categoryHtml = createCategoryHtml(category);

                if (category.type == 2) {
                    expenseList.append(categoryHtml);
                } else {
                    incomeList.append(categoryHtml);
                }
            });

            // 重新初始化拖拽排序
            initSortable();
        }

        // 创建分类HTML
        function createCategoryHtml(category) {
            // 计算子分类数量
            const subcategoryCount = category.subcategories ? category.subcategories.length : 0;
            const subcategoryText = subcategoryCount > 0 ? `(${subcategoryCount}个子分类)` : '(无子分类)';
            const categoryIcon = category.icon || '📁';

            // 安全地转义图标字符串
            const escapedIcon = categoryIcon.replace(/'/g, "\\'").replace(/"/g, '\\"');
            const escapedName = category.name.replace(/'/g, "\\'").replace(/"/g, '\\"');
            const escapedDesc = (category.description || '').replace(/'/g, "\\'").replace(/"/g, '\\"');

            return `
        <li style="display: block">
        <div class="category-item" data-id="${category.id}" data-icon="${category.icon}" data-desc="${category.description}">
            <div class="drag-handle">⋮⋮</div>
            <div class="category-info">
                <div class="category-icon" onclick="editCategoryById(${category.id})">${categoryIcon}</div>
                <div class="category-name" onclick="editCategoryById(${category.id})">
                    <span class="name-text">${category.name}</span>
                    <span class="subcategory-count">${subcategoryText}</span>
                </div>
            </div>
            <div class="category-actions">
                <button class="action-btn subcategory-btn" onclick="goToSubcategoryManagement(${category.id}, '${escapedName}')" title="管理子分类">📋</button>
                <button class="action-btn edit-btn" onclick="editCategoryById(${category.id})" title="编辑分类">✏️</button>
                <button class="action-btn delete-btn" onclick="deleteCategory(${category.id})" title="删除分类">🗑️</button>
            </div>
        </div>
        </li>
    `;
        }

        // 显示添加分类弹窗
        function showAddCategoryModal(type) {
            currentCategoryType = type;
            currentCategoryId = null;
            selectedIcon = '📁';
            initEmojiSearch('#emoji-search', '#emoji-selector', '#emoji-selector-empty', selectedIcon);
            $('#categoryModalTitle').text('添加分类');
            $('#category-name').val('');
            $('#category-description').val('');
            $('#selected-icon').text('📁');
            $('#icon-picker').hide();
            $('#categoryModal').modal('show');
        }

        // 编辑分类
        function editCategory(id, name, description, icon = '📁') {
            currentCategoryId = id;
            selectedIcon = icon;
            initEmojiSearch('#emoji-search', '#emoji-selector', '#emoji-selector-empty', selectedIcon);
            $('#categoryModalTitle').text('编辑分类');
            $('#category-name').val(name);
            $('#category-description').val(description);
            $('#selected-icon').text(icon);
            $('#icon-picker').hide();
            $('#categoryModal').modal('show');
        }

        // 通过ID编辑分类（从DOM获取数据）
        function editCategoryById(id) {
            const categoryItem = $(`.category-item[data-id="${id}"]`);
            const name = categoryItem.find('.name-text').text();
            const icon = categoryItem.data('icon') || '';
            const description = categoryItem.data('desc') || ''; // 描述需要从服务器获取或存储在DOM中
            editCategory(id, name, description, icon);
        }

        // 点击其他地方关闭图标选择器
        $(document).click(function(e) {
            if (!$(e.target).closest('.icon-selector').length) {
                $('#icon-picker').hide();
            }
        });

        // 跳转到子分类管理页面
        function goToSubcategoryManagement(categoryId, categoryName) {
            // 跳转到子分类管理页面
            window.location.href = `/user/books/{{ $book->id }}/categories/${categoryId}/subcategories`;
        }

        // 创建分类
        function createCategory() {
            const name = $('#category-name').val().trim();
            const description = $('#category-description').val().trim();

            if (!name) {
                showMessage('请输入分类名称', 'error');
                return;
            }

            const data = {
                name: name,
                type: currentCategoryType,
                description: description,
                icon: selectedIcon,
                _token: $('meta[name="csrf-token"]').attr('content')
            };

            $.post(`{{ route('user.categories.store', $book->id) }}`, data, function(response) {
                if (response.success) {
                    $('#categoryModal').modal('hide');
                    showSuccess('分类创建成功');
                    loadCategories();
                } else {
                    showError(response.message || '创建失败', response);
                }
            }).fail(function(e) {
                showError(e.responseJSON.message || '网络错误，请重试', e.responseJSON);
            });
        }

        // 更新分类
        function updateCategory() {
            const name = $('#category-name').val().trim();
            const description = $('#category-description').val().trim();

            if (!name) {
                showMessage('请输入分类名称', 'error');
                return;
            }

            const data = {
                name: name,
                description: description,
                icon: selectedIcon,
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'PUT'
            };

            $.post(`{{ route('user.categories.update', [$book->id, '']) }}/${currentCategoryId}`, data, function(response) {
                if (response.success) {
                    $('#categoryModal').modal('hide');
                    showSuccess('分类更新成功');
                    loadCategories();
                } else {
                    showError(response.message || '更新失败');
                }
            }).fail(function(e) {
                showError(e.responseJSON.message || '网络错误，请重试');
            });
        }

        // 删除分类
        function deleteCategory(id) {
            // 直接使用POST请求检查是否有记录需要迁移
            const checkData = {
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'DELETE',
                check_only: true
            };

            $.post(`{{ route('user.categories.destroy', [$book->id, '']) }}/${id}`, checkData, function(response) {
                // 如果没有交易记录和自动交易记录，直接删除
                if (response.success && !response.has_transactions && !response.has_auto_transactions) {
                    confirmDeleteCategory(id);
                }
            }).fail(function(e) {
                const responseData = e.responseJSON;

                // 检查是否需要迁移
                if (responseData && responseData.require_migration) {
                    showCategoryMigrationModal(
                        id,
                        responseData.transaction_count,
                        responseData.other_categories,
                        responseData.auto_transaction_count,
                        responseData.total_count
                    );
                } else {
                    showError(responseData.message || '网络错误，请重试');
                }
            });
        }

        // 确认删除分类
        function confirmDeleteCategory(id) {
            if (!confirm('确定要删除这个分类吗？删除后无法恢复。')) {
                return;
            }

            const data = {
                _token: $('meta[name="csrf-token"]').attr('content'),
                _method: 'DELETE'
            };

            $.post(`{{ route('user.categories.destroy', [$book->id, ':id']) }}`.replace(':id', id), data, function(response) {
                if (response.success) {
                    showSuccess('分类删除成功');
                    loadCategories();
                } else {
                    showError(response.message || '删除失败');
                }
            }).fail(function(e) {
                const responseData = e.responseJSON;

                // 检查是否需要迁移
                if (responseData && responseData.require_migration) {
                    showCategoryMigrationModal(id, responseData.transaction_count, responseData.other_categories);
                } else {
                    showError(responseData.message || '网络错误，请重试');
                }
            });
        }

        // 显示分类迁移确认弹窗
        function showCategoryMigrationModal(categoryId, transactionCount, otherCategories, autoTransactionCount, totalCount) {
            // 设置消息
            let message = '';

            if (transactionCount > 0 && autoTransactionCount > 0) {
                message = `该分类下有 ${transactionCount} 条交易记录和 ${autoTransactionCount} 条自动交易记录，请选择要迁移到的目标分类：`;
            } else if (transactionCount > 0) {
                message = `该分类下有 ${transactionCount} 条交易记录，请选择要迁移到的目标分类：`;
            } else if (autoTransactionCount > 0) {
                message = `该分类下有 ${autoTransactionCount} 条自动交易记录，请选择要迁移到的目标分类：`;
            } else {
                message = `该分类下有 ${totalCount || transactionCount} 条记录，请选择要迁移到的目标分类：`;
            }

            $('#migration-message').text(message);

            // 清空并填充目标分类下拉框
            const targetCategorySelect = $('#target-category');
            targetCategorySelect.empty();
            targetCategorySelect.append('<option value="">请选择目标分类</option>');

            otherCategories.forEach(category => {
                targetCategorySelect.append(`<option value="${category.id}">${category.icon} ${category.name}</option>`);
            });

            // 隐藏子分类选择区域
            $('#subcategory-selection-container').hide();
            $('#target-subcategory').empty().append('<option value="">请选择目标子分类</option>');

            // 当选择分类变化时，加载对应的子分类
            targetCategorySelect.off('change').on('change', function() {
                const selectedCategoryId = $(this).val();
                if (selectedCategoryId) {
                    loadSubcategoriesForMigration(selectedCategoryId);
                } else {
                    $('#subcategory-selection-container').hide();
                    $('#target-subcategory').empty().append('<option value="">请选择目标子分类</option>');
                }
            });

            // 设置确认按钮点击事件
            $('#confirm-migration').off('click').on('click', function() {
                const targetCategoryId = targetCategorySelect.val();
                const targetSubcategoryId = $('#target-subcategory').val();

                if (!targetCategoryId) {
                    showError('请选择目标分类');
                    return;
                }

                migrateAndDeleteCategory(categoryId, targetCategoryId, targetSubcategoryId);
            });

            // 显示弹窗
            $('#categoryMigrationModal').modal('show');
        }

        // 加载分类下的子分类
        function loadSubcategoriesForMigration(categoryId) {
            $.get(`{{ route('user.subcategories.data', [$book->id, ':id']) }}`.replace(':id', categoryId), function(response) {
                if (response.success && response.subcategories && response.subcategories.length > 0) {
                    const targetSubcategorySelect = $('#target-subcategory');
                    targetSubcategorySelect.empty();
                    targetSubcategorySelect.append('<option value="">请选择目标子分类</option>');

                    response.subcategories.forEach(subcategory => {
                        targetSubcategorySelect.append(`<option value="${subcategory.id}">${subcategory.icon} ${subcategory.name}</option>`);
                    });

                    $('#subcategory-selection-container').show();
                } else {
                    $('#subcategory-selection-container').hide();
                }
            }).fail(function() {
                $('#subcategory-selection-container').hide();
            });
        }

        // 迁移并删除分类
        function migrateAndDeleteCategory(sourceId, targetId, targetSubcategoryId) {
            const data = {
                _token: $('meta[name="csrf-token"]').attr('content'),
                target_category_id: targetId
            };

            // 如果选择了子分类，则添加到请求数据中
            if (targetSubcategoryId) {
                data.target_subcategory_id = targetSubcategoryId;
            }

            $.post(`{{ route('user.categories.migrate', [$book->id, ':id']) }}`.replace(':id', sourceId), data, function(response) {
                if (response.success) {
                    $('#categoryMigrationModal').modal('hide');
                    // 显示包含交易记录和自动交易记录迁移信息的成功消息
                    showSuccess(response.message || '迁移成功并删除分类');
                    loadCategories();
                } else {
                    showError(response.message || '迁移失败');
                }
            }).fail(function(e) {
                showError(e.responseJSON.message || '网络错误，请重试');
            });
        }

        // 初始化拖拽排序
        function initSortable() {
            const expenseList = document.getElementById('expense-list');
            const incomeList = document.getElementById('income-list');

            if (expenseList && expenseSortable) {
                expenseSortable.destroy();
            }

            if (incomeList && incomeSortable) {
                incomeSortable.destroy();
            }

            if (expenseList) {
                expenseSortable = Sortable.create(expenseList, {
                    handle: '.drag-handle',
                    animation: 150,
                    onEnd: function(evt) {
                        updateCategorySort(2);
                    }
                });
            }

            if (incomeList) {
                incomeSortable = Sortable.create(incomeList, {
                    handle: '.drag-handle',
                    animation: 150,
                    onEnd: function(evt) {
                        updateCategorySort(1);
                    }
                });
            }
        }

        // 更新分类排序
        function updateCategorySort(type) {
            const listId = type == 2 ? 'expense-list' : 'income-list';
            const sortData = [];

            $(`#${listId} .category-item`).each(function(index) {
                sortData.push({
                    id: $(this).data('id'),
                    sort: index + 1
                });
            });

            const data = {
                sort_data: sortData,
                _token: $('meta[name="csrf-token"]').attr('content')
            };

            $.post(`{{ route('user.categories.sort', $book->id) }}`, data, function(response) {
                if (response.success) {
                    showSuccess('排序更新成功');
                } else {
                    showError('排序更新失败');
                    loadCategories(); // 重新加载以恢复原始顺序
                }
            }).fail(function(e) {
                showError(e.responseJSON.message || '网络错误，请重试');
                loadCategories(); // 重新加载以恢复原始顺序
            });
        }

    </script>
@endpush
